﻿using System;
using System.Reflection;
using System.Windows;
using System.Windows.Interactivity;
using MvvmBase.Converters;

namespace DeepmixRadioClient.Workflow
{
    public class CallDataContextMethodAction : TriggerAction<FrameworkElement>
    {
        /// <summary>
        /// Set the method name to invoke. Method must exist at datacontext and be public
        /// </summary>
        public string MethodName { get; set; }

        /// <summary>
        /// Use this word to pass all argument as parameter
        /// "null" means that method must be with out of parameters
        /// </summary>
        public string ArgumentsPathForParameter { get; set; }

        protected override void Invoke(object eventArgs)
        {
            if (string.IsNullOrEmpty(MethodName) || AssociatedObject.DataContext == null)
            {
                return;
            }

            object dataContext = AssociatedObject.DataContext;
            Type type = dataContext.GetType();
            MethodInfo methodInfo = type.GetMethod(MethodName);
            if (methodInfo == null)
            {
                throw new MemberAccessException(
                    string.Format("Method {0} not found. Ensure that it has public instance signature", MethodName));
            }

            if (string.IsNullOrEmpty(ArgumentsPathForParameter))
            {
                methodInfo.Invoke(dataContext, new object[0]);
            }
            else
            {
                if (ArgumentsPathForParameter == "this") ArgumentsPathForParameter = string.Empty;
                object valueToPath = eventArgs.GetProperty(ArgumentsPathForParameter);
                methodInfo.Invoke(dataContext, new[] { valueToPath });
            }
        }
    }
}